package com.example.custsecurity.security.config;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//匿名用户访问未授权的资源就调用此方法
@Slf4j
@Component
public class CustAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        response.setContentType("text/html;charset=UTF-8");
        JSONObject jsonObject=new JSONObject();
        jsonObject.putOpt("code",HttpServletResponse.SC_UNAUTHORIZED);
        jsonObject.putOpt("msg","匿名用户访问受限");


        PrintWriter pw = response.getWriter();
        pw.print(jsonObject);
        pw.flush();
        pw.close();
    }
}
